package atguigu2.communicate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/3
 * @VERSION 1.0
 * @DESC
 * 实现定制化通信
 */
//一、创建资源类
class ShareResource{
    //定义变量及标识位属性等
    private int flag = 1;//设置标志位,1:AA,2:BB,3:CC
    private Lock lock  = new ReentrantLock();//可重入锁
    private Condition c1 = lock.newCondition();// 通知 AA
    private Condition c2 = lock.newCondition();// 通知 BB
    private Condition c3 = lock.newCondition();// 理解Lock及Condition,Syn如何实现呢？
    //定义操作
    public void print5(int loop) throws InterruptedException {//传入轮数 ,print5为线程AA打印
        //上锁
        lock.lock();
        // 判断
        while(flag!=1){
            c1.await();
        }
        // 干活
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"::"+i+"::"+loop);
        }
        // 通知
        flag = 2;
        c2.signal();
    }

    public void print10(int loop) throws InterruptedException {//传入轮数 ,print5为线程AA打印
        //上锁
        lock.lock();
        // 判断
        while(flag!=2){
            c2.await();
        }
        // 干活
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"::"+i+"::"+loop);
        }
        // 通知
        flag = 3;
        c3.signal();
    }

    public void print15(int loop) throws InterruptedException {//传入轮数 ,print5为线程AA打印
        //上锁
        lock.lock();
        // 判断
        while(flag!=3){
            c3.await();
        }
        // 干活
        for (int i = 0; i < 15; i++) {
            System.out.println(Thread.currentThread().getName()+"::"+i+"::"+loop);
        }
        // 通知
        flag = 1;
        c1.signal();
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.print5(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.print10(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.print15(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

    }
}
